<?php

namespace Admin\Controller;

use Admin\Model\ManageModel;
use Admin\Model\RoleModel;

class IndexController extends BaseController
{
	// 首页
	public function index()
	{
		if (session('manage')['username'] !== "admin") {
			$menuArray = C('NAV_LIST');
			$role = (new RoleModel)->getRoleById(session("manage")["role_id"]);
			$idString = $role['auth'];
			$menu_list = filterMenuArray($menuArray, $idString);
			$navList = $this->doUrl($menu_list);
			$this->assign('navList',$navList);
		} else {
			$navList = $this->doUrl(C('NAV_LIST'));
			$this->assign('navList',$navList);
		}
		$this->display();
	}

	// 处理导航URL
	protected function doUrl($navList)
	{
		foreach ($navList as $key1 => $value1) {
			$navList[$key1]['href'] = empty($value1['href']) ? "" : U($value1['href']);
			if ($value1['children']) {
				foreach ($value1['children'] as $key2 => $value2) {
					$navList[$key1]['children'][$key2]['href'] = U($value2['href']);
				}
			}
		}
		return json_encode($navList);
	}

	// 欢迎页
	public function main()
	{
		$this->display();
	}

	// 删除缓存文件夹
	public function clearcache()
	{
		/*通过删除runtime 文件夹*/
		$rtim = del_dir(APP_PATH . 'Runtime');

		if ($rtim) {
			return retJson(0, '删除成功', '');
		} else {
			return retJson(1, '未知原因，删除失败!', '');
		}
	}

	// 修改密码
	public function updpwd()
	{
		// 显示页面
		if (!IS_AJAX) return $this->display();

		// 处理数据
		$manage_model = new ManageModel();
		$oldpwd = I("post.oldpwd");
		$newpwd = I("post.newpwd");
		$okpwd = I("post.okpwd");
		if ($newpwd !== $okpwd) return retJson(1, "两次密码不一致");
		$manage_id = session('manage')['manage_id'];
		$manage_user = $manage_model->selById($manage_id);
		if (empty($manage_user)) return retJson(1, "或许用户信息失败");
		$password_md5 = $manage_user["password"];
		if (md5($oldpwd) !== $password_md5) return retJson(1, "旧密码错误");
		$data = array();
		$data["manage_id"] = $manage_id;
		$data["password"] = md5($newpwd);
		$upd_result = $manage_model->updpwd($data);
		if ($upd_result > 0) {
			return retJson(0, '修改成功');
		} else {
			return retJson(1, "修改失败");
		}
	}

	// 个人资料
	public function userinfo()
	{
		$role = (new RoleModel())->getRoleById(session('manage')['role_id']);
		$this->assign('role',$role);
		return $this->display();
	}
}
